﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using ArsenalManagement.Models;
using ArsenalManagement.Tools;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace ArsenalManagement.Controllers
{
    public class UserController : Controller
    {
        private readonly ArsenalManagementContext _context;
        private readonly ILogger<HomeController> _logger;

        public UserController(ArsenalManagementContext context, ILogger<HomeController> logger)
        {
            _context = context;
            _logger = logger;
        }

        
 

        // GET: User
        public async Task<IActionResult> Index()
        {

            return _context.Users != null ? 
                          View(await _context.Users.ToListAsync()) :
                          Problem("Entity set 'ArsenalManagementContext.Users'  is null.");
        }

        // GET: User/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null || _context.Users == null)
            {
                return NotFound();
            }

            var user = await _context.Users
                .FirstOrDefaultAsync(m => m.Id == id);
            if (user == null)
            {
                return NotFound();
            }

            return View(user);
        }

        // GET: User/Create
        public IActionResult Create()
        {
            return View();
        }

        public IActionResult Exist()
        {
            return View();
        }

        public IActionResult Login()
        {
            return View();
        }

        //登录
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Login([Bind("Id,Username,Password,Authority")] User user)
        {
            if (ModelState.IsValid)
            {
                var u = _context.Users.FirstOrDefault(m => m.Username == user.Username);
                MD5Encrypt encrypt = new MD5Encrypt();
                if (u == null)
                {
                    ViewData["msg"] = "用户名不存在！";
                    return View();
                }
                else if (u.Password == encrypt.md5(user.Password))
                {
                    HttpContext.Session.SetString("user", u.Username.ToString());
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ViewData["msg"] = "用户名或密码错误！";
                    return View();
                }
            }
            else
                return View(user);
        }

        //注册
        // POST: User/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,Username,Password,Authority")] User user)
        {
            if (ModelState.IsValid)
            {
                var u = _context.Users.FirstOrDefault(m => m.Username == user.Username);
                if (u == null)
                {
                    MD5Encrypt encrypt = new MD5Encrypt();
                    user.Password = encrypt.md5(user.Password);
                    _context.Add(user);
                    await _context.SaveChangesAsync();
                    ViewData["msg"] = "创建成功！";
                    return RedirectToAction("Index","Home");
                }
                else
                {
                    ViewData["msg"] = "用户名已存在！";
                    return View();
                }                
            }
            else
                return View(user);
        }

        // GET: User/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null || _context.Users == null)
            {
                return NotFound();
            }

            var user = await _context.Users.FindAsync(id);
            if (user == null)
            {
                return NotFound();
            }
            return View(user);
        }

        // POST: User/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Id,Username,Password,Authority")] User user)
        {
            if (id != user.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(user);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!UserExists(user.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(user);
        }

        // GET: User/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null || _context.Users == null)
            {
                return NotFound();
            }

            var user = await _context.Users
                .FirstOrDefaultAsync(m => m.Id == id);
            if (user == null)
            {
                return NotFound();
            }

            return View(user);
        }

        // POST: User/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            if (_context.Users == null)
            {
                return Problem("Entity set 'ArsenalManagementContext.Users'  is null.");
            }
            var user = await _context.Users.FindAsync(id);
            if (user != null)
            {
                _context.Users.Remove(user);
            }
            
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool UserExists(int id)
        {
          return (_context.Users?.Any(e => e.Id == id)).GetValueOrDefault();
        }
    }
}
